﻿using System;
using System.ClientModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using OpenAI;

namespace llmChat
{
    public class ai_Chat2
    {
        public async Task Chat_Loop()
        {
            // 配置加载
            var config = new ConfigurationBuilder().AddUserSecrets<ai_Chat2>().Build();
            var chatSection = config.GetSection("aliyun");

            if (!chatSection.Exists() || chatSection.GetChildren().Any(c => string.IsNullOrEmpty(c.Value)))
            {
                Console.WriteLine("配置错误: appsettings.json中aliyun节点缺失或不完整");
                return;
            }
            var chatParam = chatSection.Get<ChatModel>()!;


            // 构建客户端
            var openAIClient = new OpenAIClient(
                new ApiKeyCredential(chatParam.APIKey!),
                new OpenAIClientOptions { Endpoint = new Uri(chatParam.BaseUrl) }
            );
            using var client = openAIClient.GetChatClient(chatParam.ModelName!).AsIChatClient();
            var chatHistory = new List<ChatMessage>
            {
                new ChatMessage(ChatRole.System,"你是一个智能助手，请根据用户输入回答问题")
            };


            // 对话循环
            while (true)
            {
                try
                {
                    Console.Write("You(exit退出): ");
                    var msg = Console.ReadLine()?.Trim(); // 处理null和空字符串

                    if (string.IsNullOrEmpty(msg) || msg.Equals("exit", StringComparison.OrdinalIgnoreCase))
                        break;
                    chatHistory.Add(new ChatMessage(ChatRole.User, msg));
                    Console.Write("\nAssistant:");
                    // 流式响应处理（含异常捕获）
                    var responseBuilder = new StringBuilder();
                    await foreach (var update in client.GetStreamingResponseAsync(chatHistory).ConfigureAwait(false))
                    {
                        Console.Write(update.Text);
                        responseBuilder.Append(update.Text);
                    }
                    chatHistory.Add(new ChatMessage(ChatRole.Assistant, responseBuilder.ToString()));
                    Console.WriteLine("\n");
                }
                catch (Exception ex) // 单次对话异常处理
                {
                    Console.WriteLine($"\n[ERROR] 请求失败: {ex.Message}");
                    // 可选：移除最后一条问题上下文
                    if (chatHistory.Last().Role == ChatRole.User)
                        chatHistory.RemoveAt(chatHistory.Count - 1);
                }
            }
        }
    }
}
